<?php

namespace xcxApi\modules\guest\controllers;

use common\components\fast_api\Controller;
use common\datas\Enums;
use common\models\db\Banners;
use common\models\db\Files;
use xcxApi\models\db\Categories;

class PubController extends Controller
{
    /**
     * 这是一个测试
     * @param string $x
     * @return array
     */
    public function actionTest($x)
    {
        return $this->apiSuccess([
            'test' => $x,
        ]);
    }

    /**
     * 生成图片
     * @param string $w
     * @param string $h
     * @param string $fontSize
     * @return void
     */
    public function actionGd($w = 300, $h = null, $fontSize = 1, $fontStr = null)
    {
        if (!$h) {
            $h = $w;
        }
        if (!$fontStr) {
            $fontStr = "{$w}x{$h}";
        }
        $fontPath = \Yii::getAlias('@common/fonts/TEMPSITC.TTF');
        // 创建一个 wxh 像素的图像资源
        $image = imagecreatetruecolor($w, $h);
        // 设置背景颜色
        $white = imagecolorallocate($image, 100, 100, 100);
        // 填充背景
        imagefill($image, 0, 0, $white);
        // 设置文字颜色
        $black = imagecolorallocate($image, 150, 150, 150);
        // 添加文字（使用 GD 内置字体）
        // 第一个参数是图像资源，第二个参数是字体大小，第三个参数是文本颜色，第四个参数是文本内容
        // 第五个参数是文本在图像上的位置（x, y），这里设置为图像中心
        $textWidth = imagefontwidth($fontSize)*strlen($fontStr); // 获取字体宽度
        $textHeight = imagefontheight($fontSize); // 获取字体高度
        // 使用 imagettfbbox 获取文本的尺寸
//        $bbox = imagettfbbox($fontSize, 0, $fontPath, $fontStr);
        // 计算文本的宽度
//        $textWidth = $bbox[2] - $bbox[0];
        // 计算文本的高度
//        $textHeight = abs($bbox[1] - $bbox[7]);
        $x = ($w - $textWidth) / 2; // 计算文本水平位置
        $y = ($h - $textHeight) / 2; // 计算文本垂直位置
        imagestring($image, $fontSize, $x, $y, $fontStr, $black);
//        Tools::yiiLog("{$w}x{$h} {$textWidth}x{$textHeight} {$x}x{$y}");
        // 输出图像
        header('Content-Type: image/png');
//        \Yii::$app->response->format = Response::FORMAT_HTML;
//        \Yii::$app->response->headers->set('Content-Type', 'image/png');
        imagepng($image);
        // 销毁图像资源
        imagedestroy($image);
        exit;
    }

    /**
     * 缩略图
     * @return string
     */
    public function actionThumbImage($src)
    {
        $info = parse_url($src);
        $path = $info['path'];
        $imageRoot = '';
        if (substr($path, 0, 9) === '/storage/') {
            $_src = \Yii::getAlias('@storage_root').str_replace('/storage/', '/', $path);
            if (file_exists($_src)) {
                $imageRoot = $_src;
            }
        } elseif (substr($path, 0, 15) === '/static/images/') {
            $_src = \Yii::getAlias('@static_root').str_replace('/static/images/', '/images/', $path);
            if (file_exists($_src)) {
                $imageRoot = $_src;
            }
        }

        if (!$imageRoot) {
            $src = \Yii::getAlias('@static_aburl/images/404.jpeg');
            header('Content-Type: image/jpeg');
            readfile($src);exit;
        }

        $thumbInfo = pathinfo($imageRoot);
        $thumbInfo['filename'] = $thumbInfo['filename'].'_thumb';
        $thumbRoot = $thumbInfo['dirname'].'/'. $thumbInfo['filename'].'.jpg';

        if (file_exists($thumbRoot)) {
            header('Content-Type: image/jpeg');
            readfile($thumbRoot);exit;
        }

        $info = pathinfo($imageRoot);
        $ext = $info['extension'];

        // 读取原始图片
        switch ($ext) {
            case "jpg":
            case "jpeg":
                $srcImg = imagecreatefromjpeg($imageRoot);
                break;
            case "png":
                $srcImg = imagecreatefrompng($imageRoot);
                break;
            case "webp":
                $srcImg = imagecreatefromwebp($imageRoot);
                break;
            case "bmp":
                $srcImg = imagecreatefrombmp($imageRoot);
                break;
            case "wbmp":
                $srcImg = imagecreatefromwbmp($imageRoot);
                break;
            case "gif":
                $srcImg = imagecreatefromgif($imageRoot);
                break;
            default:
                $src = \Yii::getAlias('@static_aburl/images/404.jpeg');
                header('Content-Type: image/jpeg');
                readfile($src);exit;
        }
        $mimeType = \Yii::$app->wMimeTypes->getMimeType($ext);
        header('Content-Type: '.$mimeType);

        // 缩略图最大宽度和高度
        $maxWidth = 400;
        $maxHeight = 400;

        // 计算缩略图大小
        $srcWidth = imagesx($srcImg);
        $srcHeight = imagesy($srcImg);
        $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight);
        $newWidth = round($srcWidth * $scale);
        $newHeight = round($srcHeight * $scale);

        // 创建新的图像资源
        $newImg = imagecreatetruecolor($newWidth, $newHeight);

        // 将原始图片复制到新的图像资源中，并缩小
        imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);

        // 保存新的图像资源
        imagejpeg($newImg, $thumbRoot);
        imagejpeg($newImg);
        exit;
    }

    /**
     * 获取所有根分类
     * @desc
     * @return array
     */
    public function actionCategoryRoots()
    {
        $categories = \Yii::$app->cache->getOrSet(APP_ID."-Guest-Pub-CategoryRoots", function () {
            $categories = Categories::find()
                ->andWhere(['status' => Categories::STATUS_ACTIVE])
                ->andWhere(['is_root' => Enums::IS_TRUE])
                ->orderBy(['root_sort' => SORT_ASC])
                ->all();
            return $categories;
        }, 10);
        return $this->apiSuccess(['list' => $categories]);
    }

    /**
     * 获取所有轮播图
     * @desc
     * @return array
     */
    public function actionBannerList()
    {
        $banners = \Yii::$app->cache->getOrSet(APP_ID."-Guest-Pub-Banners", function () {
            $banners = Banners::find()
                ->andWhere(['status' => Banners::STATUS_ACTIVE])
                ->all();
            $items = [];
            foreach ($banners as $k => $v) {
                $item = $v->toArray();
//                $item['url'] = Files::thumbImageUrl($v->url);
                $items[] = $item;
            }
            return $items;
        }, 10);
        return $this->apiSuccess(['list' => $banners]);
    }
}
